import {
  Body,
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ToolsService } from 'src/utils/tools.service';
import { ExcelService } from './excel.service';

@Controller('excel')
export class ExcelController {
  constructor(private readonly excelService: ExcelService) {}

  //文件上传
  @Post('analyze')
  @UseInterceptors(FileInterceptor('file')) //获取header的file文件
  //从UploadedFile可获取
  async analyze(@UploadedFile() file, @Body() body) {
    try {
      //图片命名空间
      const namespace = body.namespace
        ? body.namespace.replace(/\s+/g, '')
        : '';
      const workbook = await this.excelService.readExcel(file.buffer);
      const worksheet = workbook.worksheets[0];
      const rows = [];
      worksheet.eachRow((row) => {
        const rowData = [];
        row.eachCell((cell) => {
          rowData.push(cell.value);
        });
        rows.push(rowData);
      });
      console.log('.........', JSON.stringify(rows));
      // 下面自己进行逻辑处理，也可以为了防止报错，使用try...catch...

      return JSON.stringify(rows)
    } catch (error) {
      ToolsService.fail(error);
    }
  }
}
